/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2009-12 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus.utilities;

import static com.google.common.io.Files.*;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author alb  (based originally on code by Atul S. Khot (ask)
 */
public class Filename
{
    /**
     * Returns extension if any in the filename
     * @param filename filename with possible extension
     * @return  the extension (less the leading .) or if there is no extension, the empty string.
     */
    public static String getExtension( final String filename )
    {
        if( filename != null )
            return( getFileExtension( filename ));
        return( "" );
    }

    /**
     * Extracts the base name of a file. So: /home/you/wiggle.jar -> wiggle
     * @param filename the full filename including path for the file
     * @return the base name.
     * @throws NullPointerException if filename is null
     */
    public static String getBaseName( final String filename )
    {
        String filepath = getFilenameMinusExtension( filename );

        int fslash = filepath.lastIndexOf( "/");
        int bslash = filepath.lastIndexOf( "\\" );
        int endOfPath = fslash > bslash ? fslash: bslash;
        if( endOfPath == -1 )   // if no slashes of either kind found in path...
            return( filepath );
        else
            return( filepath.substring( endOfPath+1 ));
    }

    /**
     * Returns filename without the extension
     * @param filename with possible extension
     * @return filename w/out extension
     * @throws NullPointerException if filename is null
     */
    public static String getFilenameMinusExtension( final String filename )
    {
        String filepath = checkNotNull( filename );
        final String extension = getExtension( filepath );
        if( extension.length() > 0 )
            filepath = TextTransforms.truncate( filename, extension.length() + ".".length() );
        return( filepath );
    }
}
